package com.kbs.im.server.bootstrap;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty服务启动类
 *
 * @author zhangzhang
 */
public class ImServerBootStrap {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ImServerBootStrap.class);

    /**
     * 服务端启动类实例
     */
    public static final ImServerBootStrap INSTANCE = new ImServerBootStrap();

    /**
     * 服务启动端口
     */
    private static final int PORT = 6666;

    /**
     * 用于接收处理连接的线程组
     */
    private static final EventLoopGroup BOSS_GROUP = new NioEventLoopGroup();

    /**
     * 用于接收处理每个连接请求的线程组
     */
    private static final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup();

    /**
     * 服务器启动辅助实例
     */
    private static final ServerBootstrap SERVER_BOOTSTRAP = new ServerBootstrap();

    /**
     * 启动服务
     */
    public void run() {
        try {
            SERVER_BOOTSTRAP
                    //指定线程模型
                    .group(BOSS_GROUP, WORKER_GROUP)
                    //指定IO模型
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(ImServerChannelInitializer.INSTANCE);
            ChannelFuture future = SERVER_BOOTSTRAP.bind(PORT).sync();
            LOGGER.info("服务已启动,端口:[" + PORT + "]");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            LOGGER.error("服务启动异常。", e);
        } finally {
            WORKER_GROUP.shutdownGracefully();
            BOSS_GROUP.shutdownGracefully();
        }
    }


}
